import pymysql
from settings.mysqlM import db


class Acl:
    def __init__(self) -> None:
        pass

    # 给用户添加权限
    def set_resource(self, uid, reslist):
        for i in reslist:
            sql = "insert into user_resources(userid,resourceid) values({},{})".format(int(uid), int(i))
            db.update(sql)

    # 修改权限
    def update_resource(self, uid, reslist):
        # 先删除原来的在重新添加
        sql = "select userid from user_resources where userid={}".format(int(uid))
        res = db.find_all(sql)
        if res:
            sql1 = "delete from user_resources where userid={}".format(int(uid))
            db.update(sql1)
            self.set_resource(uid, reslist)
        else:
            self.set_resource(uid, reslist)

    # 删除某个权限
    def delete_resource(self, uid, reourseid):
        sql = "delete from user_resources where userid={} and resourceid={}".format(int(uid), int(reourseid))
        db.update(sql)

    # 获取页面资源列表
    def get_page_reslist(self, uid):
        sql = "select r.url as url from user_resources as u,resources as r where u.userid={} and r.type=1 and u.resourceid=r.id".format(
            int(uid))
        res = db.find_all(sql)
        lst = []
        for i in res:
            lst.append(i['url'])

        return lst

    # 获取接口资源列表
    def get_interface_reslist(self, uid):
        sql = "select r.url as url from user_resources as u,resources as r where u.userid={} and r.type=2 and u.resourceid=r.id".format(
            int(uid))
        res = db.find_all(sql)
        lst = []
        for i in res:
            lst.append(i['url'])

        return lst


acl = Acl()